package com.cn.psys.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.psys.base.BaseResponse;
import com.cn.psys.jhfb.imp.Jhfb;
import com.cn.psys.mybatisplus.MybatisPlusQuery;
import com.cn.psys.system.entity.JhfbPro;
import com.cn.psys.system.entity.JhfbStu;
import com.cn.psys.system.service.IJhfbProService;
import com.cn.psys.system.service.IJhfbStuService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Controller
public class FileUploadController {
    @Autowired
    private IJhfbProService targetService;

    @Autowired
    private IJhfbStuService targetServiceStu;
    /*
     * 获取file.html页面
     */
    @RequestMapping("file")
    public String file(){
        return "/file";
    }
    @RequestMapping("uploadFile")
    @ResponseBody
    public BaseResponse uploadFile(@RequestParam("fileName") MultipartFile file){

            File dest = null;
            //页面上传的文件后缀，包含.
            String fileType = null;
            //文件保存到硬盘的文件名
            String fileSaveName = null;
            //文件保存全路径
            String fullSavePath = null;
            try{
                if(file.isEmpty()){
                    return BaseResponse.success("文件为空");
                }
                String fileName = file.getOriginalFilename();
                int size = (int) file.getSize();
                System.out.println(fileName + "-->" + size);

                //String path = "/Users/zhuwei" ;
                String path = ResourceUtils.getURL("classpath:").getPath();
                System.out.println("------path"+path);
                if (fileName.indexOf(".") > -1) {
                    int index = fileName.split("\\.").length;
                    if (index > 0) {
                        fileType = "." + fileName.split("\\.")[index - 1];
                    }
                } else {
                    fileType = "";
                }
                fileSaveName = IdUtil.randomUUID()  +  fileType;
                fullSavePath = path + "static/uploadFile/" + fileSaveName;
                //File upload = new File(path.getAbsolutePath(),"static/images/upload/");
                dest = new File(fullSavePath);
                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
            }catch (Exception e){
                e.printStackTrace();;
            }

            try {
                file.transferTo(dest); //保存文件
                String proId = IdUtil.randomUUID();
                Map<String,List<JhfbStu>> resMap = new HashMap<>();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return BaseResponse.error("上传失败");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return BaseResponse.error("上传失败");
            }
        return BaseResponse.success("上传成功",fullSavePath);
        }

    /**
     * 分班实现
     * */
    @RequestMapping("divide")
    @ResponseBody
    public BaseResponse fileUpload(@RequestParam("fullSavePath") String fullSavePath,@RequestParam("proName") String proName
            ,@RequestParam("classNum") int classNum,@RequestParam("sexFlag") String sexFlag,@RequestParam("nationFlag") String nationFlag,
                                   @RequestParam("graduateSchoolFlag") String graduateSchoolFlag,@RequestParam("errorVal") String errorVal){
        try{
            String proId = IdUtil.randomUUID();
            Map<String,List<JhfbStu>> resMap = new HashMap<>();
            for(int i = 0;i<2000;i++){
                resMap = Jhfb.dotask(proName,classNum,sexFlag,nationFlag,fullSavePath);
                List<BigDecimal> list = new ArrayList<>();
                for (String key : resMap.keySet()) {
                    BigDecimal all_score = new BigDecimal(0);
                    List<JhfbStu> stu_tmp = resMap.get(key);
                    for (JhfbStu tmp : stu_tmp) {
                        all_score = all_score.add(new BigDecimal(tmp.getAllScore()));
                    }
                    list.add(all_score.divide(new BigDecimal(
                            stu_tmp.size()), 2, BigDecimal.ROUND_HALF_UP));
                }
                System.out.println("--------第"+i+"次计算");
                //list中的元素排序
                Jhfb.sortAbs(list);
                //最大值减去最小值，误差小于设定误差就跳出循环，否则进行下次循环
                if(list.get(0).subtract(list.get(list.size()-1)).abs().compareTo(new BigDecimal(errorVal))==-1){
                    break;
                }
            }

            if (resMap.size()>0){
                // 计算平均数
                int studentM_num = 0;
                int studentW_num = 0;
                for (String key : resMap.keySet()) {
                    BigDecimal all_score = new BigDecimal(0);
                    List<JhfbStu> stu_tmp = resMap.get(key);
                    studentM_num = 0;
                    studentW_num = 0;
                    for (JhfbStu tmp : stu_tmp) {
                        all_score = all_score.add(new BigDecimal(tmp.getAllScore()));
                        if ("男".equals(tmp.getSex().trim())) {
                            studentM_num++;
                        } else {
                            studentW_num++;
                        }
                        tmp.setUuid(IdUtil.randomUUID());
                        tmp.setProId(proId);
                        tmp.setCreateTime(DateUtil.now());
                        targetServiceStu.save(tmp);
                    }
                    System.out.println(key
                            + "的平均分是："
                            + String.valueOf(all_score.divide(new BigDecimal(
                            stu_tmp.size()), 2, BigDecimal.ROUND_HALF_UP))
                            + "; 男生人数：" + studentM_num + "  女生人数：" + studentW_num);
                }
                //编班返回数据
                JhfbPro jhfbPro_obj = new JhfbPro();
                jhfbPro_obj.setUuid(proId);
                jhfbPro_obj.setTaskName(proName);
                jhfbPro_obj.setClassNum(classNum);
                jhfbPro_obj.setFileSavePath(fullSavePath);
                jhfbPro_obj.setCreateTime(DateUtil.now());
                jhfbPro_obj.setSex(Integer.parseInt(sexFlag));
                jhfbPro_obj.setNation(Integer.parseInt(nationFlag));
                jhfbPro_obj.setGraduateSchool(Integer.parseInt(graduateSchoolFlag));
                jhfbPro_obj.setCreateUser((String) SecurityUtils.getSubject().getPrincipal());
                targetService.save(jhfbPro_obj);
                return BaseResponse.success("编班成功");
            }else{
                return BaseResponse.error("请增加允许误差值");
            }

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return BaseResponse.error("上传失败");
        }
    }

    /**
     * java对象的集合自定义排序
     *
     * @param list
     * @return
     */
    public static List<BigDecimal> sortList(List<BigDecimal> list) {

        Collections.sort(list, new Comparator<BigDecimal>() {
            @Override
            public int compare(BigDecimal obj1, BigDecimal obj2) {

                if (obj1.compareTo(obj2)> 0 ){
                    return -1;
                } else {
                    return 1;
                }
            }
        });
        return list;
    }
    /**
     * 重新分班
     * */
    @RequestMapping("redivide")
    @ResponseBody
    public BaseResponse fileUpload(@RequestParam("fileSavePath") String fileSavePath,@RequestParam("proName") String proName
            ,@RequestParam("classNum") int classNum,@RequestParam("sexFlag") String sexFlag,@RequestParam("proId") String proId,
                                   @RequestParam("nationFlag") String nationFlag,@RequestParam("graduateSchoolFlag") String graduateSchoolFlag,@RequestParam("errorVal") String errorVal){

        try {
            Map<String,List<JhfbStu>> resMap = new HashMap<>();
            for(int i = 0;i<2000;i++){
                resMap = resMap = Jhfb.dotask(proName,classNum,sexFlag,nationFlag,fileSavePath);
                List<BigDecimal> list = new ArrayList<>();
                for (String key : resMap.keySet()) {
                    BigDecimal all_score = new BigDecimal(0);
                    List<JhfbStu> stu_tmp = resMap.get(key);
                    for (JhfbStu tmp : stu_tmp) {
                        all_score = all_score.add(new BigDecimal(tmp.getAllScore()));
                    }
                    list.add(all_score.divide(new BigDecimal(
                            stu_tmp.size()), 2, BigDecimal.ROUND_HALF_UP));
                }
                System.out.println("--------第"+i+"次计算");
                Jhfb.sortAbs(list);
                if(list.get(0).subtract(list.get(list.size()-1)).abs().compareTo(new BigDecimal(errorVal))==-1){
                    break;
                }
                resMap.clear();
            }

            if (resMap.size()>0){
                // 先删除所有该工程的学生数据
                String paramData = "[{column: \"pro_id\",type: \"eq\", value: \""+proId+"\"}]";
                QueryWrapper<JhfbStu> queryWrapper = MybatisPlusQuery.parseWhereSql(paramData);
                boolean res = targetServiceStu.remove(queryWrapper);
                for (String key : resMap.keySet()) {
                    List<JhfbStu> stu_tmp = resMap.get(key);
                    for (JhfbStu tmp : stu_tmp) {
                        tmp.setUuid(IdUtil.randomUUID());
                        tmp.setProId(proId);
                        tmp.setCreateTime(DateUtil.now());
                        targetServiceStu.save(tmp);
                    }
                }
                //编班返回数据
                JhfbPro jhfbPro_obj = targetService.getById(proId);
                jhfbPro_obj.setTaskName(proName);
                jhfbPro_obj.setClassNum(classNum);
                jhfbPro_obj.setSex(Integer.parseInt(sexFlag));
                jhfbPro_obj.setNation(Integer.parseInt(nationFlag));
                targetService.updateById(jhfbPro_obj);
                return BaseResponse.success("编班成功");
            }else{
                return BaseResponse.error("请增加允许误差值");
            }

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return BaseResponse.error("系统报错，请联系管理员！");
        }
    }

    /*
     * 获取multifile.html页面
     */
    @RequestMapping("multifile")
    public String multifile(){
        return "/multifile";
    }

    /**
     * 实现多文件上传
     * */
    @RequestMapping(value="multifileUpload",method= RequestMethod.POST)
    /**public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files) */
    public @ResponseBody BaseResponse multifileUpload(HttpServletRequest request){

        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");

        if(files.isEmpty()){
            return BaseResponse.error("文件为空");
        }

        String path = null;
        try {
            path = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            if(file.isEmpty()){
                return BaseResponse.error("文件为空");
            }else{
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                }catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return BaseResponse.error("上传失败");
                }
            }
        }
        return BaseResponse.success("上传成功");
    }
}
